package com.mms.interceptor;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class LoginFilter
 */

public class LoginFilter implements Filter {

    /**
     * Default constructor. 
     */
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
	    HttpServletRequest req=(HttpServletRequest)request;
	    request.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html;charset=UTF-8");
	    HttpServletResponse resp=(HttpServletResponse) response;
	    String requestUri = req.getRequestURI();  
	    if (req.getSession().getAttribute("userName")!=null&&!req.getSession().getAttribute("userName").equals("")) {
	     // pass the request along the filter chain
	        chain.doFilter(request, response);
        }
	    else if (req.getParameter("name")!=null&&req.getParameter("name")!="") {
	        chain.doFilter(request, response);
        }
	    else  if (requestUri.endsWith("login.jsp")||requestUri.endsWith("getAllDepartments.action")||requestUri.endsWith("register.action")) {
            chain.doFilter(req, resp);
        }
	    else 
        {
	        req.setAttribute("isLoginLegal", false);
	        resp.sendRedirect("login.jsp");
        }
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
